import { observer } from 'mobx-react-lite';
import { useEffect, useLayoutEffect } from 'react';
import { useLocation, useSearchParams } from 'react-router-dom';
import { useNavigation } from '@/hooks';
import { useGlobalStore, useUserInfoStore } from '@/mobx';
import { noSignAceRouter } from '@/constants';
import { postAppConfig, postBalance } from '@/services';
import { ssSetItem } from '@/utils';

// 身份状态认证
const Authority = observer(() => {
  const { userInfo, updateBalance } = useUserInfoStore();
  const { updateAppConfig } = useGlobalStore();
  const navigation = useNavigation();
  const { pathname } = useLocation();
  const [searchParms] = useSearchParams();
  const ivt_code = searchParms.get('ic');

  // 处理邀请码
  useEffect(() => {
    if (ivt_code) {
      ssSetItem('ivt_code', ivt_code);
    }
  }, [ivt_code]);

  useEffect(() => {
    if (userInfo?.Token) {
      // 获取用户余额
      postBalance({})
        .then((res: any) => {
          updateBalance(res?.Data);
        })
        .catch(() => {});
    }
  }, [updateBalance, userInfo?.Token]);

  useEffect(() => {
    // 获取客服列表
    postAppConfig({})
      .then((res: any) => {
        updateAppConfig(res?.Data);
      })
      .catch(() => {});
  }, [updateAppConfig]);

  useLayoutEffect(() => {
    // 已经登录过，跳转登录/注册页则直接转接到首页
    if (userInfo?.Token && ['/login', '/register'].includes(pathname)) {
      navigation('/', { replace: true });
    } else if (!userInfo?.Token && !noSignAceRouter.test(pathname)) {
      navigation('/login', { replace: true });
    }
  }, [navigation, pathname, userInfo?.Token]);

  return null;
});

export default Authority;
